<template>
  <div class="release_form_dialog">
    <el-dialog
      v-model="visible"
      :title="dialogTitle"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="30vh"
      center
      width="500px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="100px"
            size="small"
          >
            <el-form-item v-if="isAddChild" label="父级名称">
              <div>{{ form.parentName }}</div>
            </el-form-item>

            <el-form-item label="模块名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入"
                maxlength="100"
                size="small"
              ></el-input>
            </el-form-item>

            <el-form-item label="排序编号" prop="orderNumber">
              <el-input
                v-model="form.orderNumber"
                maxlength="9"
                placeholder="请输入"
                size="small"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance, computed } from "vue";
import { ElMessage } from "element-plus";

const initFormData = () => {
  return {
    id: null,
    name: null,
    orderNumber: null,
    parentId: null,
    parentName: null,
    orgId: null,
  };
};

export default {
  name: "ProjectModuleFormDialog",
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      name: [{ required: true, message: "请输入模块名称", trigger: "blur" }],
    });

    const isEdit = ref(false);
    const isAddChild = ref(false);

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          confirmBtnLoading.value = true;
          $api.cascade
            .addCascade(form)
            .then((res) => {
              confirmBtnLoading.value = false;
              ElMessage.success("操作成功！");
              // 触发事件，把数据传递给父组件
              context.emit("refresh");
              close();
            })
            .catch((err) => {
              confirmBtnLoading.value = false;
              console.error("saveOrUpdate error: ", err);
            });
        } else {
          return false;
        }
      });
    };

    // 打开弹框
    const open = (orgId, row, isAdd = false) => {
      if (!orgId) {
        return console.error("缺少参数 orgId");
      }
      form.orgId = orgId;
      if (row) {
        if (isAdd) {
          // 添加下级
          form.parentId = row.id;
          form.parentName = row.name;
        } else {
          // 编辑
          form.id = row.id;
          form.name = row.name;
          form.parentId = row.parentId;
          form.orderNumber = row.orderNumber;
        }
        isEdit.value = true;
      } else {
        // 新增
        isEdit.value = false;
      }
      isAddChild.value = isAdd;
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    // 弹框名称
    const dialogTitle = computed(() => {
      let title = "";
      if (isAddChild.value) {
        title = "添加下级模块";
      } else if (isEdit.value) {
        title = "编辑模块";
      } else {
        title = "新建模块";
      }
      return title;
    });

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      form,
      rules,
      open,
      close,
      handleConfirm,
      isEdit,
      isAddChild,
      dialogTitle,
    };
  },
};
</script>

<style lang="less" scoped>
.dialog_container {
}
.dialog_footer {
}
</style>
